/***********************************************************************************
**  
* @copyright (c) 2010-2019, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
************************************************************************************/
/**
* @file	    mjs_auth_action.cpp
* @version     
* @brief      
* @author   duye
* @date	    2016-12-26
* @note 
*
* 1. 2016-12-26 duye Created this file
*/

#include <string>
#include <duye_type.h>
#include <duye_logger.h>
#include <mj_net_protocol.h>
#include <mjs_inner_msg.h>
#include <mjs_mysql.h>
#include <mjs_reqer.h>
#include <mjs_auth_action.h>

static const int8* DUYE_LOG_PREFIX = "mangjings.action.auth";

MJSAuthAction::MJSAuthAction() {}
MJSAuthAction::~MJSAuthAction() {}

bool MJSAuthAction::onAction(MJMsgAction* action, MJSReqer* reqer) {
	if (!action || !reqer) {
		DUYE_ERROR("action == NULL || reqer == NULL");
		notify(reqer, MJS_INNER_AUTH_FA);
		return false;
	}

	if (action->getName() != "auth") {
		DUYE_ERROR("action_name != 'auth");
		notify(reqer, MJS_INNER_AUTH_FA);
		return false;
	}

	std::string client_ip = action->getValue("ip");
	std::string user = action->getValue("user");
	std::string pwdmd5 = action->getValue("pwdmd5");

	DUYE_TRACE("request >>> client_ip=%s user=%s pwdmd5=%s", client_ip.c_str(), user.c_str(), pwdmd5.c_str());

	MJSMysqlResult result;
	std::string sql = "SELECT COUNT(1) AS num FROM userinfo WHERE phone = ? and passwd = ?";
	MJSMysql::ins().query(sql, MJSMysql::Params(user, pwdmd5), result);
	
	// response client
	MJMsgAction resp_action;
	if (!MJMsgFactory::ins().createAction(action->getName(), resp_action)) {
		DUYE_ERROR("createAction 'auth' failed");
		notify(reqer, MJS_INNER_AUTH_FA, user.c_str());
		return true;
	}

	MJSInnerMsgType inner_msg_type = MJS_INNER_MAX;
	
	resp_action.setValue("ip", client_ip);
	resp_action.setValue("user", user);
	if (result.row() > 0) {
		DUYE_INFO("user:%s authentication success", user.c_str());
		resp_action.setValue("result", "success");
		inner_msg_type = MJS_INNER_AUTH_OK;
	} else {
		DUYE_WARN("user:%s authentication failure", user.c_str());
		resp_action.setValue("result", "failure");
		resp_action.setValue("desc", "user or password wrong");
		inner_msg_type = MJS_INNER_AUTH_FA;
	}

	std::string msg_xml;
	MJMsgFactory::ins().createMsgXml(resp_action, msg_xml);
	if (!reqer->sendToClient(msg_xml)) {
		DUYE_ERROR("sendToClient failed");
		notify(reqer, MJS_INNER_AUTH_FA, user.c_str());
		return false;
	}

	// notify client proxy
	return notify(reqer, inner_msg_type, user.c_str());
}

bool MJSAuthAction::notify(MJSReqer* reqer, MJSInnerMsgType type, const int8* data) {
	if (!reqer->notify(type, (void*)(data))) {
		DUYE_ERROR("notify failed");
		return false;
	}

	return true;
}